Creating maintainable JavaScript code is important if want to keep using the code.
In this article, we’ll look at the basics of creating maintainable JavaScript code by looking at the best ways to handle errors.
try-catch
We should never have try-catch
statements with an empty block.
They should be handled in some way so that our code won’t fail silently.
For instance, we don’t write:
try {
errorFunc();
} catch (ex) {
// do nothing
}
We don’t want to ignore errors.
Error Types
The ES specification specifies several kinds of built-in errors type.
Error
is the base constructor for all errors.
EvalError
throws when an error occurs during execution of eval
.
RangeError
is throw when a number is outside the bounds of its range.
They rarely occur during normal execution.
ReferenceError
is thrown when an object is expected but it’s not available.
SyntaxError
is thrown when code has a syntax error.
TypeError
is thrown when a variable is of an unexpected type.
URIError
is thrown when the URI we passed into encodeURI
, encodeURIComponent
, decodeURI
, or decodeURIComponrnt
is incorrectly formatted.
If we understand the different types of errors, then it’s easy to handle them.
All error types inherit from error.
And if we check for specific types of errors, we get better error handling.
For instance, we can write:
try {
// ...
} catch (ex) {
if (ex instanceof TypeError) {
// ...
} else if (ex instanceof ReferenceError) {
// ...
} else {
// handle all others
}
}
We check which type of error is thrown with the instanceof
operator, and we can write error-handling code for each kind of error.
Throwing Error
instances have their advantages.
Error
objects thrown are handled by browser’s error handling mechanism.
There’s also extra information in the Error
object like the line and column number and stack trace.
If we want to throw custom errors, we can create our own Error
class.
For instance, we can write:
class MyError extends Error {
constructor(message) {
super();
this.message = message;
}
}
We used the extends
keyword to create a subclass of Error
.
Then we can use it by writing:
throw new MyError('error occurred');
Now if we throw the error, then it’ll respond like any native error.
Most modern browsers will handle them the same way so we don’t have to worry about browser compatibility.
With our own error class, we can check for the error type by writing:
try {
// ...
} catch (ex) {
if (ex instanceof MyError) {
// ...
} else {
// handle all others
}
}
We check the error type with instanceof
like any other error.
Conclusion
We can create our own error class so that we can include the information we want in the error.
Also, we check for the type of error that’s thrown with the instanceof
operator.
JavaScript has several types of built-in error types.